#include "Tcpsever.hpp"
#include "Http.hpp"
#include <memory>
#include <string>
#include <unistd.h>

std::string SuffixTOtype(const std::string &suffix)
{
    if(suffix == ".html" || suffix == ".html")
        return "text/html";
    else if(suffix == ".png")
        return "image/png";
    else if(suffix == ".jpg")
        return "image/jpg";
    else
        return "text/html";
        
}

std::string CodeDesc(int code)
{
    switch(code)
    {
        case 200:
            return "ok";
        case 301:
            return "Moved Permanently";//永久性重定向
        case  307:
            return "Temporary Redirect";
        case 404:
            return "Not Found";
        case 403:
            return "Forbidden";
        case 500:
            return "Internal Sever Error";
        default:
            return "unknow";
    }
    return "";
}

std::string HandlerHttpRequest(std::string &request)
{
    //std::cout << request << std::endl;
    HttpRequest http;
    HttpRespose resq;
    http.Deserialization(request);
    http.Parse();
    http.Debugghttp();
    int code =200;

    std::string content;
    content = http.GetfileContent();
    if(content.empty())
    {
        code = 404; 
        http.Get_404();
    }
    code = 307;
    resq.setcode(code);
    resq.set_desc(CodeDesc(code));
    resq.Makestatsline();
    std::string content_len_str = "Content-length: " + std::to_string(content.size()) + "\r\n";//正文长度 
    resq.AddHeader(content_len_str);
    // std::string location = "Location: https:/www.bilibili.com/\r\n";//重定向
    // resq.AddHeader(location);
    std::string content_type = "Content-type: " +  SuffixTOtype(http.Getsuffix()) + "\r\n";
    resq.AddHeader(content_type);
    resq.Addcontent(content);
    std::string httpresponse = resq.Serilize();

    // std::string httpstatusline = "Http/1.0 200 OK\r\n";
    // std::string httpheader = "Content-Length: " + SuffixTOtype(http.Getsuffix()) +"\r\n";
    // httpheader += "\r\n";

    
    // std::string httpresponse = httpstatusline + httpheader + content;
    return httpresponse;
}

int main(int argc, char **argv)
{
    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<Tcpsever> hp(new Tcpsever(port, HandlerHttpRequest));
    hp->Loop();
    return 0;
}